unit BaseXML;

interface

uses
   XMLIntf, XMLDoc, SysUtils, xmldom, msxmldom, Variants;

type

  TAccessXML = class
  protected
    FXMLDocument: IXMLDocument;
    FXMLFile: string;
    function CreateXMLDoc: IXMLDocument;
    function TrimVar(AValue: OleVariant): string;
    function ChildNodesToStr(AXMLNode: IXMLNode): string;
    procedure Init; virtual;
  public
    procedure OpenXML(AXMLFile: String);
    procedure SaveToFile(AXMLFile: String);
    constructor Create(); overload; virtual;
    constructor Create(AXMLFile: string); overload; virtual;
    destructor Destroy; override;
  end;

implementation

{ TAccessXML }

function TAccessXML.ChildNodesToStr(AXMLNode: IXMLNode): string;
var
  I, J: Integer;
begin
  if AXMLNode.HasChildNodes then
  begin
    Result := '';
    for I := 0 to AXMLNode.ChildNodes.Count - 1 do
    begin
      if AXMLNode.ChildNodes.Nodes[I].HasChildNodes then
      begin
        Result := Result + '<' + AXMLNode.ChildNodes.Nodes[I].NodeName;
        for J := 0 to  AXMLNode.ChildNodes.Nodes[I].AttributeNodes.Count -1 do
        begin
          Result := Result + ' ' + AXMLNode.ChildNodes.Nodes[I].AttributeNodes.Nodes[J].NodeName +
            '="'+ AXMLNode.ChildNodes.Nodes[I].AttributeNodes.Nodes[J].NodeValue + '" ';
        end;
        Result := Result + '>'
      end;
      
      Result := Result + ChildNodesToStr(AXMLNode.ChildNodes.Nodes[I]);
      if AXMLNode.ChildNodes.Nodes[I].HasChildNodes then
        Result := Result + '</' + AXMLNode.ChildNodes.Nodes[I].NodeName + '>' ;
    end;
  end
  else
  begin
    Result := AXMLNode.NodeValue;
  end;
end;

constructor TAccessXML.Create(AXMLFile: string);
begin
  Create();
  OpenXML(AXMLFile);
  Init;
end;

constructor TAccessXML.Create;
begin
  FXMLDocument := CreateXMLDoc;
end;

function TAccessXML.CreateXMLDoc: IXMLDocument;
var
  mXMLDoc: TXMLDocument;
begin
  mXMLDoc := TXMLDocument.Create(nil);
  mXMLDoc.DOMVendor := MSXML_DOM;
  Result := mXMLDoc;
end;

destructor TAccessXML.Destroy;
begin
  FXMLDocument := nil;
  inherited;
end;

procedure TAccessXML.Init;
begin

end;

procedure TAccessXML.OpenXML(AXMLFile: String);
begin
  FXMLFile := AXMLFile;
  FXMLDocument.LoadFromFile(AXMLFile);
  FXMLDocument.Active := True;
end;

procedure TAccessXML.SaveToFile(AXMLFile: String);
begin
  FXMLDocument.SaveToFile(AXMLFile);
end;

function TAccessXML.TrimVar(AValue: OleVariant): string;
begin
  if VarIsNull(AValue) then
    Result := ''
  else
    Result := Trim(AValue);
end;

end.
